package com.chun.service.impl;

import com.chun.mapper.DeptMapper;
import com.chun.mapper.EmpMapper;
import com.chun.pojo.Dept;

import com.chun.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpMapper empMapper;
//    @Autowired
//    private DeptLogService deptLogService;

    @Override
    public List<Dept> list() {
        List<Dept> deptList = deptMapper.list();
        return deptList;
    }

    /**
     * 根据id删除部门以及下面的员工
     *
     * @param id
     */
    //添加属性：rollbackFor = Exception.class，所有的异常都能回滚
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(Integer id) throws Exception {
        // 先删除该部门下的所有员工
        empMapper.deleteByDeptId(id);
        // 再删除部门
        deptMapper.delete(id);
        
        // 记录删除日志
//        DeptLog deptLog = new DeptLog();
//        deptLog.setCreateTime(LocalDateTime.now());
//        deptLog.setDescription("根据id删除部门，id=" + id);
//        deptLogService.insert(deptLog);
    }

    @Override
    public void add(Dept dept) {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.add(dept);
    }

    @Override
    public Dept getgetDeptById(Integer id) {
        Dept dept = deptMapper.getDeptById(id);
        return dept;
    }

    @Override
    public void update(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.update(dept);
    }
}
